using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using System.Net.Http;
using DotNetCore.MyBlogApp.DataModel;
using Microsoft.Extensions.Configuration;

namespace DotNetCore.MyBlogApp.Controllers
{
    public class IndexController : Controller
    {
        private readonly IConfiguration configuration;
        private readonly string apiHost;
        public IndexController(IConfiguration configuration)
        {
            this.configuration = configuration;
            apiHost = this.configuration.GetSection("ApiHost").Value;
        }
        public IActionResult Index(int page = 0, int pageSize = 10)
        {
            ViewData["pageIndex"] = page == 0 ? 1 : page;
            if (page > 0) page--;
            var url = $"{apiHost}/article?pageindex={page}&pagesize={pageSize}";
            HttpClient httpClient = new HttpClient();
            var data = httpClient.GetStringAsync(url).GetAwaiter().GetResult();
            var list = Newtonsoft.Json.JsonConvert.DeserializeObject<List<dynamic>>(data);
            ViewData.Add("articles", list);
            return View();
        }


        public IActionResult Article()
        {
            return View();
        }
        public IActionResult Article_Full(string id)
        {
            if (string.IsNullOrEmpty(id))
                return View();
            var url = $"{apiHost}/article/{id}";
            var result = new HttpClient().GetStringAsync(url).GetAwaiter().GetResult();
            var data = Newtonsoft.Json.JsonConvert.DeserializeObject<dynamic>(result);
            ViewData.Add("article", data);
            return View(data);
        }

        public IActionResult Gallery()
        {
            return View();
        }
    }
}